package com.netease.qa.web.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author zoudongdong
 * @date 2018/3/8
 * 检查用户的登录状态,如果session中的loginUser为null,则跳转到登录页面
 */

public class UserInterceptor extends HandlerInterceptorAdapter {

    private static Logger log = LoggerFactory.getLogger(UserInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("********UserInterceptor preHandle***********");

        //如果是登录页面的请求,则放行
        String requestUrl = request.getRequestURI();
        if (requestUrl.equals("/lego/loginIndex") || requestUrl.equals("/lego/userLogin") ||
                requestUrl.equals("/lego/userRegisterIndex") || requestUrl.equals("/lego/userRegister")) {
            return true;
        }

        HttpSession session = request.getSession();
        if (session.getAttribute("loginUser") == null) {
            //没有登录,跳转到登录页面
            request.getRequestDispatcher("/lego/loginIndex").forward(request, response);
            return false;
        } else {
            //用户已经登录了,放行
            return true;
        }
    }
}
